package com.ruoyi.web.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Program: RuoYi-Vue-chy->TaskService
 * @Description: 处理多线程的一个service
 * @Author: hongyu.chen
 * @Date: 2025-03-06 15:59
 * @Version： 1.0
 **/
@Service
public class TaskServiceImpl implements TaskService{

    private static final Logger logger = LoggerFactory.getLogger(TaskService.class);
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    //为了确保线程安全，我们将使用ConcurrentHashMap来存储任务结果。
    private final Map<String, String> taskResults = new ConcurrentHashMap<>();

    @Override
    public void processTask(String taskDetails) {
        threadPoolExecutor.execute(() -> {
            try {
                // 模拟任务处理时间
                Thread.sleep(10000);
                String result = "Processed " + taskDetails;
                //为了确保线程安全，我们将使用ConcurrentHashMap来存储任务结果。
                taskResults.put(taskDetails, result);
                System.out.println("Processed task: " + taskDetails + " by " + Thread.currentThread().getName());
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // 恢复中断状态
                System.err.println("Task processing interrupted: " + taskDetails);
            }
        });
        System.out.println("Processed task1111: " + taskDetails );
    }

    @Override
    public String getTaskResult(String taskDetails) {
        return taskResults.get(taskDetails);
    }

    @Async("taskExecutor")
    @Override
    public void processTaskAsync(String taskId) {
        try {
            // 模拟任务处理时间
            Thread.sleep(10000);
            String result = "Processed " + taskId;
            taskResults.put(taskId, result);
            logger.info(result + " by " + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.error("Task processing interrupted: " + taskId, e);
        }
        System.out.println("Processed task2222: " + taskId );

    }
}
